package org.elec.mac.controller;

import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Element;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.constants.Constants;
import org.elec.mac.entity.*;
import org.elec.mac.page.PageList;
import org.elec.mac.page.PageProperty;
import org.elec.mac.service.*;
import org.elec.mac.utils.JSONUtil;
import org.elec.mac.utils.MenuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by Bean on 2017/5/16.
 */
@Slf4j
@Controller
public class SysController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRoleUserService sysRoleUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysActionService sysActionService;

    @Autowired
    private SysRoleActionService sysRoleActionService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Value("${role.menu.id}")
    private String roleMenuId;

    @Value("${role.action.id}")
    private String roleActionId;

    @Value("${role.id}")
    private String roleIds;

    @RequestMapping(value = "/user_list.do")
    public String userListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                  @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                  @RequestParam(value = "limit", required = false)String limit,
                                  @RequestParam(value = "page", required = false)String page) throws IOException {
        String startdate = this.getParameter(request, "startdate");
        String enddate = this.getParameter(request, "enddate");
        String username = this.getParameter(request, "username");
        // 分页信息
        if("page".equals(action)) {
            PageProperty pp = new PageProperty();
            if(StringUtils.isNotBlank(username)) {
                pp.getParamMap().put("username", username);
            }
            if(StringUtils.isNotBlank(startdate) && StringUtils.isNotBlank(enddate)) {
                pp.getParamMap().put("startdate", startdate);
                pp.getParamMap().put("enddate", enddate);
            }
            this.setPageInfo(request.getCookies(), pp, limit, page);
            PageList<Map<String, Object>> userPageList = sysUserService.getUserInfoPageList(pp);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("records", userPageList.getRecords());
            map.put("recordsTotal", userPageList.getTotalRecords());
            map.put("recordsFiltered", userPageList.getTotalRecords());
            response.getWriter().write(JSONUtil.object2json(map));
            return null;
        }
        model.put("username", username);
        model.put("startdate", startdate);
        model.put("enddate", enddate);

        return "/sys/user_list";
    }

    @RequestMapping("/user_add.do")
    public void userAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                               @RequestParam(value = "action", required = false, defaultValue = "")String action) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("open".equals(action)) {
            try {
                EhCacheCacheManager manager = cacheConfiguration
                        .ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
                // 获取用户角色
                Cache userCache = manager.getCache("userCache");
                SysUser sysUser = userCache.get(this.getSessionUsername(request), SysUser.class);
                Cache roleUserCache = manager.getCache("roleUserCache");
                Long roleId = roleUserCache.get(sysUser.getId(), Long.class);
                // 角色列表
                Cache cache = manager.getCache("roleCache");
                List<SysRole> roleList = cache.get("roleCache", ArrayList.class);
                StringBuilder builder = new StringBuilder();
                if(roleList != null && roleList.size() > 0) {
                    builder.append("<option value=\"\">---请选择---</option>");
                    for(SysRole role : roleList) {
                        if(role.getId() != Long.parseLong(roleIds) && (role.getId() > roleId)) {
                            builder.append("<option value=\"" + role.getId() + "\">");
                            builder.append(role.getRoleName());
                            builder.append("</option>");
                        }
                    }
                }
                result.getBody().put("roleList", builder.toString());
            }
            catch (Exception e) {
                log.error("用户新增错误", e);
                result.setSuccess(false);
                result.setMsg("用户新增错误");
            }
        }
        if("do".equals(action)) {
            //
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String confirmpass = request.getParameter("confirmpass");
            String role = request.getParameter("role");
            // 验证重复用户
            EhCacheCacheManager manager = cacheConfiguration
                    .ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
            Cache cache = manager.getCache("userCache");
            SysUser user = cache.get(username, SysUser.class);
            // 当前用户角色
            Cache roleUserCache = manager.getCache("roleUserCache");
            Long roleId = roleUserCache.get(user.getId(), Long.class);
            if(user != null) {
                result.setSuccess(false);
                result.setMsg("用户已存在");
            }
            // 参数验证
            if(result.isSuccess()) {
                result = this.getResult(result, username, password, confirmpass, role, roleId);
            }
            // 保存数据
            if(result.isSuccess()) {
                try {
                    // 保存新增用户
                    SysUser sysUser = new SysUser();
                    sysUser.setUsername(username);
                    sysUser.setPassword(DigestUtils.md5Hex(password));
                    sysUser.setPname(username);
                    sysUser.setIsValid(Constants.IS_VALID_TRUE);
                    sysUser.setEmail("");
                    sysUser.setPhone("");
                    sysUser.setSex(1);
                    sysUser.setTel("");
                    sysUser.setCreator(getSessionUsername(request));
                    sysUser.setCreateTime(new Date());
                    sysUser.setModifier(getSessionUsername(request));
                    sysUser.setModifyTime(new Date());
                    sysUserService.insert(sysUser);
                    // 保存用户-角色关系
                    SysRoleUser sysRoleUser = new SysRoleUser();
                    sysRoleUser.setUserId(sysUser.getId());
                    sysRoleUser.setRoleId(Long.parseLong(role));
                    sysRoleUser.setCreator(getSessionUsername(request));
                    sysRoleUser.setCreateTime(new Date());
                    sysRoleUserService.insert(sysRoleUser);
                    /** 保存至缓存 **/
                    // 用户缓存
                    cache.put(sysUser.getUsername(), sysUser);
                    // 用户-角色缓存
                    cache = manager.getCache("roleUserCache");
                    cache.put(sysUser.getId(), sysRoleUser.getRoleId());
                }
                catch(Exception ex) {
                    log.error("用户新增错误", ex);
                    result.setSuccess(false);
                    result.setMsg("用户新增错误");
                }
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping("/user_set_role.do")
    public void userSetRoleHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                @RequestParam(value = "id", required = true, defaultValue = "0")String id,
                                @RequestParam(value = "username", required = true)String username) throws IOException {
        //
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        EhCacheCacheManager manager = cacheConfiguration
                .ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        Cache cache = manager.getCache("userCache");
        SysUser user = cache.get(username, SysUser.class);
        String sessionName =  getSessionUsername(request);
        // 防止恶意删除admin信息(修改者不为admin)
        if (!this.getAttack(result, username, sessionName).isSuccess()) {
            log.info(JSONUtil.object2json(result));
            response.getWriter().write(JSONUtil.object2json(result));
            return;
        }
        //
        if("edit".equals(action)) {
            try {
                //
                if (user == null) {
                    result.setSuccess(false);
                    result.setMsg("用户修改错误-没有找到用户信息");
                }
                if(result.isSuccess()) {
                    // 获取用户角色
                    Cache userCache = manager.getCache("userCache");
                    SysUser sysUser = userCache.get(this.getSessionUsername(request), SysUser.class);
                    Cache roleUserCache = manager.getCache("roleUserCache");
                    Long roleId = roleUserCache.get(sysUser.getId(), Long.class);
                    // 角色列表
                    cache = manager.getCache("roleCache");
                    List<SysRole> roleList = cache.get("roleCache", ArrayList.class);
                    StringBuilder bulider = new StringBuilder();
                    if(roleList != null && roleList.size() > 0) {
                        bulider.append("<option value=\"\">---请选择---</option>");
                        for(SysRole role : roleList) {
                            if(role.getId() != Long.parseLong(roleIds) && (role.getId() > roleId)) {
                                bulider.append("<option value=\"" + role.getId() + "\">");
                                bulider.append(role.getRoleName());
                                bulider.append("</option>");
                            }
                        }
                    }
                    result.getBody().put("roleList", bulider.toString());
                    result.getBody().put("roleId", roleId);
                    result.getBody().put("user", user);
                }
            }
            catch (Exception ex) {
                log.error("用户角色修改错误", ex);
                result.setSuccess(false);
                result.setMsg("用户角色修改错误");
            }
        }
        if("doEdit".equals(action)) {
            String role = request.getParameter("role");
            //
            if(StringUtils.isBlank(id)) {
                result.setSuccess(false);
                result.setMsg("用户编号不能为空");
            }
            //
            if(user == null) {
                result.setSuccess(false);
                result.setMsg("用户修改错误-没有找到用户信息");
            }
            if(result.isSuccess() && (StringUtils.isBlank(role) || "0".equals(role))) {
                result.setSuccess(false);
                result.setMsg("权限不能为空");
            }
            if(result.isSuccess()) {
                try {
                    // 删除用户角色
                    Map<String, Object> params = new HashMap<>();
                    params.put("userId", Long.parseLong(id));
                    sysRoleUserService.deleteSysRoleUserByUserId(params);
                    // 重新生成角色
                    SysRoleUser sysRoleUser = new SysRoleUser();
                    sysRoleUser.setUserId(Long.parseLong(id));
                    sysRoleUser.setRoleId(Long.parseLong(role));
                    sysRoleUser.setCreateTime(new Date());
                    sysRoleUser.setCreator(getSessionUsername(request));
                    sysRoleUserService.insert(sysRoleUser);
                    // 更新用户-角色缓存
                    cache = manager.getCache("roleUserCache");
                    cache.put(user.getId(), Long.parseLong(role));
                    // 更新用户菜单
                    MenuUtil mu = new MenuUtil();
                    mu.initMenu(request, manager, this.getSession(request));
                }
                catch (Exception ex) {
                    log.error("用户角色修改数据保存错误", ex);
                    result.setSuccess(false);
                    result.setMsg("用户角色修改数据保存错误");
                }
            }
        }
        if("doDelete".equals(action)) {
            //
            if(StringUtils.isBlank(id)) {
                result.setSuccess(false);
                result.setMsg("用户编号不能为空");
            }
            //
            if(user == null) {
                result.setSuccess(false);
                result.setMsg("用户删除错误-没有找到用户信息");
            }
            if(result.isSuccess()) {
                try {
                    // 保存数据
                    SysUser sysUser = new SysUser();
                    sysUser.setId(Long.parseLong(id));
                    sysUser.setModifier(getSessionUsername(request));
                    sysUser.setModifyTime(new Date());
                    sysUser.setIsValid(Constants.IS_VALID_FALSE);
                    sysUserService.update(sysUser);
                    // 删除用户角色
                    Map<String, Object> params = new HashMap<>();
                    params.put("userId", sysUser.getId());
                    sysRoleUserService.deleteSysRoleUserByUserId(params);
                    // 移除用户缓存
                    cache.evict(username);
                    // 移除用户-角色缓存
                    cache = manager.getCache("roleUserCache");
                    cache.evict(sysUser.getId());
                    // 移除用户-菜单缓存
                    cache = manager.getCache("userMenuCache");
                    cache.evict(username);
                }
                catch (Exception ex) {
                    log.error("用户删除数据保存错误", ex);
                    result.setSuccess(false);
                    result.setMsg("用户删除数据保存错误");
                }
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping("/edit_password.do")
    public void editPassHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                  @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                  @RequestParam(value = "username", required = true)String username) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        String sessionName =  getSessionUsername(request);
        // 防止恶意删除admin信息(修改者不为admin)
        if (!this.getAttack(result, username, sessionName).isSuccess()) {
            log.info(JSONUtil.object2json(result));
            response.getWriter().write(JSONUtil.object2json(result));
            return;
        }
        if("doEdit".equals(action)) {
            result = this.editPass(result, username, this.getParameter(request, "password"),
                    this.getParameter(request, "confirmpass"), getSessionUsername(request));
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping("/edit_password_self.do")
    public String editPassSelfHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                    @RequestParam(value = "action", required = false, defaultValue = "")String action) throws IOException {
        if("doEdit".equals(action)) {
            ExecuteResult result = new ExecuteResult();
            result.setSuccess(true);
            result.setMsg("成功");
            result = this.editPass(result, getSessionUsername(request), this.getParameter(request, "password"),
                    this.getParameter(request, "confirmpass"), getSessionUsername(request));
            log.info(JSONUtil.object2json(result));
            response.getWriter().write(JSONUtil.object2json(result));
            return null;
        }
        return "/sys/edit_pass_self";
    }

    @RequestMapping("/role_list.do")
    public String roleListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                  @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                  @RequestParam(value = "limit", required = false)String limit,
                                  @RequestParam(value = "page", required = false)String page) throws IOException {
        if("page".equals(action)) {
            PageProperty pp = new PageProperty();
            this.setPageInfo(request.getCookies(), pp, limit, page);
            PageList<SysRole> userPageList = sysRoleService.getPageList(pp);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("records", userPageList.getRecords());
            map.put("recordsTotal", userPageList.getTotalRecords());
            map.put("recordsFiltered", userPageList.getTotalRecords());
            log.info(JSONUtil.object2json(map));
            response.getWriter().write(JSONUtil.object2json(map));
            return null;
        }
        return "/sys/role_list";
    }

    @RequestMapping("/role_add.do")
    public void roleAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                               @RequestParam(value = "action", required = false, defaultValue = "")String action) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("do".equals(action)) {
            String rolename = request.getParameter("rolename");
            String rolememo = request.getParameter("rolememo");
            if(StringUtils.isBlank(rolename) || StringUtils.isBlank(rolememo)) {
                result.setSuccess(false);
                result.setMsg("角色名称与角色描述不能为空");
            }
            if(result.isSuccess()) {
                try {
                    SysRole sysRole = new SysRole();
                    sysRole.setRoleName(rolename);
                    sysRole.setRoleMemo(rolememo);
                    sysRole.setCreator(getSessionUsername(request));
                    sysRole.setCreateTime(new Date());
                    sysRole.setModifier(getSessionUsername(request));
                    sysRole.setModifyTime(new Date());
                    sysRoleService.insert(sysRole);
                }
                catch (Exception e) {
                    log.error("角色新增错误", e);
                    result.setSuccess(false);
                    result.setMsg("角色新增错误");
                }
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping("/role_edit.do")
    public void roleEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                @RequestParam(value = "id", required = true, defaultValue = "0")String id) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("edit".equals(action)) {
            if("0".equals(id)) {
                result.setSuccess(false);
                result.setMsg("角色编号不能为空");
            }
            if(result.isSuccess()) {
                // 角色信息
                Map<String, Object> params = new HashMap<>();
                params.put("id", id);
                try {
                    SysRole sysRole = sysRoleService.get(params);
                    result.getBody().put("sysRole", sysRole);
                }
                catch (Exception ex) {
                    log.error("角色修改错误", ex);
                    result.setSuccess(false);
                    result.setMsg("角色修改错误");
                }
            }
        }
        if("doEdit".equals(action)) {
            String rolename = request.getParameter("rolename");
            String rolememo = request.getParameter("rolememo");
            if("0".equals(id)) {
                result.setSuccess(false);
                result.setMsg("角色编号不能为空");
            }
            if(result.isSuccess()) {
                Map<String, Object> params = new HashMap<>();
                params.put("id", id);
                try {
                    SysRole sysRole = new SysRole();
                    sysRole.setId(Long.parseLong(id));
                    sysRole.setRoleName(rolename);
                    sysRole.setRoleMemo(rolememo);
                    sysRole.setModifier(getSessionUsername(request));
                    sysRole.setModifyTime(new Date());
                    sysRoleService.update(sysRole);
                }
                catch (Exception ex) {
                    log.error("角色修改保存错误", ex);
                    result.setSuccess(false);
                    result.setMsg("角色修改保存错误");
                }
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping("/role_delete.do")
    public void roleDeleteHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                  @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                  @RequestParam(value = "id", required = true, defaultValue = "0")String id) throws Exception {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("doDelete".equals(action)) {
            if("0".equals(id)) {
                result.setSuccess(false);
                result.setMsg("角色编号不能为空");
            }
            if(result.isSuccess()) {
                try {
                    Long roleId = Long.parseLong(id);
                    sysRoleService.deleteRole(roleId);
                    // 清理缓存
                    EhCacheCacheManager manager = cacheConfiguration
                            .ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
                    Cache cache = manager.getCache("roleCache");
                    // 清理角色缓存
                    List<SysRole> sysRoleList = cache.get("roleCache", ArrayList.class);
                    for(SysRole sysRole : sysRoleList) {
                        if(sysRole.getId() == roleId) {
                            sysRoleList.remove(sysRole);
                            break;
                        }
                    }
                    cache.put("roleCache", sysRoleList);
                    // 清理用户-角色缓存
                    cache = manager.getCache("roleUserCache");
                    net.sf.ehcache.Ehcache ehcache = (net.sf.ehcache.Ehcache) manager.getCache("roleUserCache").getNativeCache();
                    for (Object key : ehcache.getKeys()) {
                        Element element = ehcache.get(key);
                        Long role_Id = (Long) element.getObjectValue();
                        if(role_Id == roleId) {
                            cache.evict(key);
                            break;
                        }
                    }
                    // 清理角色-菜单缓存
                    cache = manager.getCache("roleMenuCache");
                    cache.evict(roleId);
                    // 清理角色-功能缓存
                    cache = manager.getCache("roleActionCache");
                    cache.evict(roleId);
                }
                catch (Exception ex) {
                    log.error("角色删除错误", ex);
                    result.setSuccess(false);
                    result.setMsg("角色删除错误");
                }
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    @RequestMapping("/role_set_menu.do")
    public String roleSetMenuHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                     @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                     @RequestParam(value = "id", required = true, defaultValue = "0")String id) throws IOException {
        if (!this.getAttackMenu(Long.parseLong(id), getSessionUsername(request))) {
            return "/login_out.do";
        }
        EhCacheCacheManager cacheManager = cacheConfiguration
                .ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        if("roleSetMenu".equals(action)) {
            ExecuteResult result = new ExecuteResult();
            result.setSuccess(true);
            result.setMsg("成功");
            if ("0".equals(id)) {
                String[] array = this.getParameters(request, "menuValue");
                if (array != null && array.length > 0) {
                    List<SysRoleMenu> roleMenuList = new ArrayList<>();
                    List<SysMenu> menus = new ArrayList<>();
                    // 移除角色-菜单关联
                    Map<String, Object> params = new HashMap<>();
                    params.put("roleId", Long.parseLong(id));
                    sysRoleMenuService.deleteSysRoleMenuByRoleId(params);
                    // 保存角色菜单关联
                    List<SysMenu> menuList = sysMenuService.list(new HashMap<>());
                    for (String arr : array) {
                        for (SysMenu sysMenu : menuList) {
                            if (sysMenu.getId().equals(Long.parseLong(arr))) {
                                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                                sysRoleMenu.setRoleId(Long.parseLong(id));
                                sysRoleMenu.setMenuId(sysMenu.getId());
                                sysRoleMenu.setCreator(getSessionUsername(request));
                                sysRoleMenu.setCreateTime(new Date());
                                menus.add(sysMenu);
                                roleMenuList.add(sysRoleMenu);
                            }
                        }
                    }
                    sysRoleMenuService.insertRoleMenuBatch(roleMenuList);
                    // 缓存更新
                    Cache cache = cacheManager.getCache("roleMenuCache");
                    // 移除角色缓存
                    cache.evict(Long.parseLong(id));
                    // 重新提交角色缓存
                    cache.put(Long.parseLong(id), menus);
                }
            }
            else {
                result.setSuccess(false);
                result.setMsg("角色编号不能为空");
            }
            log.info(JSONUtil.object2json(result));
            response.getWriter().write(JSONUtil.object2json(result));
            return null;
        }
        if("list".equals(action)) {
            if (!"0".equals(id)) {
                Cache cache = cacheManager.getCache("roleMenuCache");
                List<SysMenu> sysMenuList = cache.get(Long.parseLong(id), ArrayList.class);
                //
                List<SysMenu> menuList = sysMenuService.list(new HashMap<>());
                //
                List<Map<String, Object>> menus = new ArrayList<>();
                for(SysMenu parentMenu : menuList) {
                    Map<String, Object> parentParams = new HashMap<>();
                    // 父菜单
                    if(parentMenu.getParentMenuId() == 0) {
                        // 父菜单对应的子菜单
                        parentParams.put("id", Long.toString(parentMenu.getId()));
                        parentParams.put("text", parentMenu.getMenuName());
                        parentParams.put("href", parentMenu.getMenuName());
                        List<Map<String, Object>> childs = new ArrayList<>();
                        for(SysMenu childMenu : menuList) {
                            if(parentMenu.getId().equals(childMenu.getParentMenuId())) {
                                Map<String, Object> childParams = new HashMap<>();
                                childParams.put("id", Long.toString(childMenu.getId()));
                                childParams.put("text", childMenu.getMenuName());
                                childParams.put("href", childMenu.getMenuName());
                                if(sysMenuList != null && sysMenuList.size() > 0) {
                                    // 选中判断
                                    for (SysMenu sysMenu : sysMenuList) {
                                        if (sysMenu.getId().equals(childMenu.getId())) {
                                            Map<String, Object> prop = new HashMap<>();
                                            prop.put("checked", true);
                                            childParams.put("state", prop);
                                        }
                                    }
                                }
                                childs.add(childParams);
                            }
                        }
                        String[] tags = {Integer.toString(childs.size())};
                        parentParams.put("tags", tags);
                        parentParams.put("nodes", childs);
                        if(sysMenuList != null && sysMenuList.size() > 0) {
                            for(SysMenu sysMenu : sysMenuList) {
                                if(sysMenu.getId().equals(parentMenu.getId())) {
                                    Map<String, Object> prop = new HashMap<>();
                                    prop.put("checked", true);
                                    parentParams.put("state", prop);
                                }
                            }
                        }
                        menus.add(parentParams);
                    }
                }
                log.info(JSONUtil.object2json(menus));
                model.put("menuList", JSONUtil.object2json(menus));
                model.put("id", id);
            }
        }
        return "/sys/role_set_menu";
    }

    @RequestMapping("/role_set_action.do")
    public String roleSetActionHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                       @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                       @RequestParam(value = "id", required = true, defaultValue = "0")String id) throws IOException {
        EhCacheCacheManager cacheManager = cacheConfiguration
                .ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        if (!this.getAttackAction(Long.parseLong(id), getSessionUsername(request))) {
            return "/login_out.do";
        }
        if("roleSetAction".equals(action)) {
            ExecuteResult result = new ExecuteResult();
            result.setSuccess(true);
            result.setMsg("成功");
            if (!"0".equals(id)) {
                result.getBody().put("id", id);
                // 验证数组不为空
                String[] array = this.getParameters(request, "actionValue");
                if(array != null && array.length > 0) {
                    List<SysRoleAction> roleActionList = new ArrayList<>();
                    List<SysAction> actions = new ArrayList<>();
                    // 保存角色权限关联
                    List<SysAction> actionList = sysActionService.list(new HashMap<>());
                    for(String arr : array) {
                        for(SysAction sysAction : actionList) {
                            if(sysAction.getActionCode().equals(Long.parseLong(arr))) {
                                SysRoleAction sysRoleAction = new SysRoleAction();
                                sysRoleAction.setActionCode(sysAction.getActionCode());
                                sysRoleAction.setRoleId(Long.parseLong(id));
                                sysRoleAction.setCreator(getSessionUsername(request));
                                sysRoleAction.setCreateTime(new Date());
                                actions.add(sysAction);
                                roleActionList.add(sysRoleAction);
                            }
                        }
                    }
                    // 移除角色-功能关联
                    Map<String, Object> params = new HashMap<>();
                    params.put("roleId", Long.parseLong(id));
                    sysRoleActionService.deleteSysRoleActionByRoleId(params);
                    // 重新生成角色-功能关联
                    sysRoleActionService.insertRoleActionBatch(roleActionList);
                    // 缓存更新
                    Cache cache = cacheManager.getCache("roleActionCache");
                    // 移除角色缓存
                    cache.evict(Long.parseLong(id));
                    // 重新提交角色缓存
                    cache.put(Long.parseLong(id), actions);
                }
            }
            else {
                result.setSuccess(false);
                result.setMsg("角色编号不能为空");
            }
            log.info(JSONUtil.object2json(result));
            response.getWriter().write(JSONUtil.object2json(result));
            return null;
        }
        if("list".equals(action)) {
            if (!"0".equals(id)) {
                Cache cache = cacheManager.getCache("roleActionCache");
                List<SysAction> actions = cache.get(Long.parseLong(id), ArrayList.class);
                List<SysAction> actionList = sysActionService.list(new HashMap<>());
                StringBuilder builder = new StringBuilder();
                for(SysAction sysAction : actionList) {
                    boolean bool = false;
                    if(actions != null && actions.size() > 0) {
                        for(SysAction action1 : actions) {
                            if(action1.getActionCode().equals(sysAction.getActionCode())) {
                                bool = true;
                                break;
                            }
                        }
                    }
                    builder.append("<option value=\"" + sysAction.getActionCode() + "\"");
                    if(bool)
                        builder.append(" selected=\"selected\"");
                    builder.append(">" + sysAction.getActionName() + "[" + sysAction.getActionCode() + "]" +
                     "(" + sysAction.getDescription() + ")</option>");
                }
                model.put("actionList", builder.toString());
                model.put("id", id);
            }
        }
        return "/sys/role_set_action";
    }

    /**
     * 密码修改
     * @param result
     * @param username
     * @param password
     * @param confirmpass
     * @return
     */
    public ExecuteResult editPass(ExecuteResult result, String username, String password, String confirmpass, String edituser) {
        //
        EhCacheCacheManager manager = cacheConfiguration
                .ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
        Cache cache = manager.getCache("userCache");
        SysUser user = null;
        //
        if(StringUtils.isBlank(username)) {
            result.setSuccess(false);
            result.setMsg("用户名不能为空");
        }
        //
        if(result.isSuccess()) {
            try {
                user = cache.get(username, SysUser.class);
                // 验证用户有效性
                if(user == null) {
                    result.setSuccess(false);
                    result.setMsg("用户不存在");
                }
            }
            catch (Exception ex) {
                result.setSuccess(false);
                result.setMsg("修改用户密码验证用户有效性错误");
            }
        }
        // 恶意修改密码
        if(result.isSuccess() && !username.equals(edituser)) {
            result.setSuccess(false);
            result.setMsg("修改密码不合法");
        }
        //
        if(result.isSuccess() && (StringUtils.isBlank(password) || !(password.length() >= 6 && password.length() <= 12))) {
            result.setSuccess(false);
            result.setMsg("密码为空或者输入错误(大于等于6位小于等于12位数字字母)");
        }
        if(result.isSuccess() && (StringUtils.isBlank(confirmpass) || !(confirmpass.length() >= 6 && confirmpass.length() <= 12))) {
            result.setSuccess(false);
            result.setMsg("确认密码为空或者输入错误(大于等于6位小于等于12位数字字母)");
        }
        //
        if(result.isSuccess() && !password.equals(confirmpass)) {
            result.setSuccess(false);
            result.setMsg("两次输入密码不一致");
        }

        if(result.isSuccess()) {
            try {
                // 保存新增用户
                SysUser sysUser = new SysUser();
                sysUser.setId(user.getId());
                sysUser.setPassword(DigestUtils.md5Hex(password));
                sysUser.setModifier(edituser);
                sysUser.setModifyTime(new Date());
                sysUserService.update(sysUser);
                /** 保存至缓存 **/
                // 用户缓存
                user.setPassword(sysUser.getPassword());
                user.setModifier(sysUser.getModifier());
                user.setModifyTime(sysUser.getModifyTime());
                cache.put(sysUser.getUsername(), user);
            }
            catch(Exception ex) {
                log.error("用户修改密码错误", ex);
                result.setSuccess(false);
                result.setMsg("用户修改密码错误");
            }
        }


        return result;
    }

    /**
     * 参数验证
     * @param result
     * @param username
     * @param password
     * @param confirmpass
     * @param role
     * @return
     */
    public ExecuteResult getResult(ExecuteResult result, String username, String password, String confirmpass, String role, Long roleId) {
        //
        if(StringUtils.isBlank(username) || !(username.length() >= 5 && username.length() <= 12)) {
            result.setSuccess(false);
            result.setMsg("用户名为空或者输入错误");
        }
        //
        if(result.isSuccess() && (StringUtils.isBlank(password) || !(password.length() >= 6 && password.length() <= 12))) {
            result.setSuccess(false);
            result.setMsg("密码为空或者输入错误(大于等于6位小于等于12位数字字母)");
        }
        //
        if(result.isSuccess() && (StringUtils.isBlank(confirmpass) || !(confirmpass.length() >= 6 && confirmpass.length() <= 12))) {
            result.setSuccess(false);
            result.setMsg("确认密码为空或者输入错误(大于等于6位小于等于12位数字字母)");
        }
        //
        if(result.isSuccess() && !password.equals(confirmpass)) {
            result.setSuccess(false);
            result.setMsg("两次输入密码不一致");
        }
        //
        if(result.isSuccess() && (StringUtils.isBlank(role) || "0".equals(role))) {
            result.setSuccess(false);
            result.setMsg("权限不能为空");
        }
        // 恶意强行加载超级管理员权限
        if(result.isSuccess() && (role.equals(roleIds))) {
            result.setSuccess(false);
            result.setMsg("无法加载该用户角色");
        }
        // 用户角色不为下级
        if(result.isSuccess() && (Long.parseLong(role) <= roleId)) {
            result.setSuccess(false);
            result.setMsg("用户角色配置错误");
        }
        return result;
    }

    /**
     * 防止用户进行恶意操作，删除admin信息
     * 如果登录用户不为admin，而被修改用户为admin返回错误
     * @param session 操作人
     * @param username 被修改人
     * @return
     */
    public ExecuteResult getAttack(ExecuteResult result, String session, String username) {

        if(!username.equals(Constants.SYSTEM_ADMIN) && !session.equals(Constants.SYSTEM_ADMIN)) {
            result.setSuccess(false);
            result.setMsg("无权修改该用户信息");
            return result;
        }

        return result;
    }

    /**
     *
     * @param roleId
     * @param session
     * @return
     */
    public Boolean getAttackMenu(Long roleId, String session) {
        if (roleId == Long.parseLong(roleMenuId) && session.equals(Constants.SYSTEM_ADMIN)) {
            return true;
        }
        return false;
    }

    /**
     *
     * @param roleId
     * @param session
     * @return
     */
    public Boolean getAttackAction(Long roleId, String session) {
        if (roleId == Long.parseLong(roleActionId) && session.equals(Constants.SYSTEM_ADMIN)) {
            return true;
        }
        return false;
    }
}
